package com.tp;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.TimePickerDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class Restaurant extends CustomWindow implements OnClickListener,
		TextWatcher {
	DateFormat fmtDateAndTime = DateFormat.getDateTimeInstance();
	EditText resTime;
	TextView res_selected, all_res_selected;
	View line;
	AutoCompleteTextView resName;
	static String res_select = "";
	Button nextRes, setDate;
	Button submit;
	static JSONObject jObj;
	static JSONArray jArr;
	static int flag; // flag =1 goi tu Create, 2 goi tu EditTrip
	ArrayList<String> arr;
	Calendar dateAndTime = Calendar.getInstance();
	TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
			dateAndTime.set(Calendar.MINUTE, minute);
			updateTime();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_restaurant);
		this.icon.setImageResource(R.drawable.restaurant);
		this.title.setText("Restaurant");
		setDate = (Button) findViewById(R.id.setDateRes);
		setDate.setOnClickListener(this);
		nextRes = (Button) findViewById(R.id.next_res);
		nextRes.setOnClickListener(this);
		submit = (Button) findViewById(R.id.submit_res);
		submit.setOnClickListener(this);
		resName = (AutoCompleteTextView) findViewById(R.id.res_name);
		resTime = (EditText) findViewById(R.id.res_time);
		arr = getRes();
		resName.addTextChangedListener(this);
		resName.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, arr));
		line = (View) findViewById(R.id.line1);
		res_selected = (TextView) findViewById(R.id.res_selected);

		all_res_selected = (TextView) findViewById(R.id.all_res_selected);
		if (!res_select.equals("")) {
			line.setVisibility(1);
			all_res_selected.setText(res_select);
		}
		updateTime();

	}

	public ArrayList<String> getRes() {
		// END Convert response to string
		JSONArray jArray;
		JSONObject json_data = null;
		int i;
		ArrayList<String> r = new ArrayList<String>();
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters
				.add(new BasicNameValuePair("id_Type", String.valueOf(2)));
		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/ObjectController/getAllObjectByType", postParameters);

			jArray = new JSONArray(result);
			jArr = jArray;
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				// Log.d("A", json_data.getString("name"));
				r.add(json_data.getString("name"));
			}
			// return r;
		} catch (JSONException e1) {
			Toast.makeText(this, e1.toString(), Toast.LENGTH_SHORT).show();
		} catch (ParseException e1) {
			Toast.makeText(this, e1.toString(), Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return r;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.text.TextWatcher#afterTextChanged(android.text.Editable)
	 */
	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.text.TextWatcher#beforeTextChanged(java.lang.CharSequence,
	 * int, int, int)
	 */
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.text.TextWatcher#onTextChanged(java.lang.CharSequence, int,
	 * int, int)
	 */
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		// res_select += resName.getText().toString() + "\n";
		res_selected.setText(resName.getText());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_restaurant, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {

		// TODO Auto-generated method stub
		int i;
		switch (v.getId()) {
		case R.id.next_res:
			if (!resName.getText().toString().equals("")) {
				for (i = 0; i < arr.size(); i++) {
					if (arr.get(i).equals(resName.getText().toString()))
						break;
				}
				if (i == arr.size())
					addNewRes(resName.getText().toString());
				res_select += res_selected.getText().toString() + " luc "
						+ resTime.getText().toString() + "\n";
				all_res_selected.setText(res_select);
				if (flag == 1) {
					Create.items[1] += "\n" + resName.getText().toString()
							+ " luc " + resTime.getText().toString();
					startActivity(new Intent(this, Restaurant.class));
				} else {
					EditTrip.items[1] += "\n" + resName.getText().toString()
							+ " luc " + resTime.getText().toString();
					startActivity(new Intent(this, Restaurant.class));
				}
			}
			break;
		case R.id.setDateRes:
			new TimePickerDialog(this, t,
					dateAndTime.get(Calendar.HOUR_OF_DAY),
					dateAndTime.get(Calendar.MINUTE), true).show();
			break;
		case R.id.submit_res:
			if (!resName.getText().toString().equals("")) {
				for (i = 0; i < arr.size(); i++) {
					if (arr.get(i).equals(resName.getText().toString()))
						break;
				}
				if (i == arr.size())
					addNewRes(resName.getText().toString());
				if (flag == 1) {
					Create.time = resTime.getText().toString();
					Create.items[1] += "\n" + resName.getText().toString()
							+ " luc " + resTime.getText().toString();

					Create.tripName.setText(Create.name);
					Create.startDate.setText(Create.date);
					res_select = "";
					startActivity(new Intent(this, Create.class));
				} else {
					EditTrip.ini = 0;
					EditTrip.items[1] += "\n" + resName.getText().toString()
							+ " luc " + resTime.getText().toString();

					EditTrip.tripName.setText(EditTrip.name);
					EditTrip.startDate.setText(EditTrip.date);
					res_select = "";
					startActivity(new Intent(this, EditTrip.class));
				}
			}
			break;

		}
	}

	private void addNewRes(String string) {
		// TODO Auto-generated method stub

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("name", string));
		postParameters.add(new BasicNameValuePair("id_User", Integer
				.toString(Constant.user)));
		postParameters
				.add(new BasicNameValuePair("id_Type", String.valueOf(2)));

		String result = null;
		try {

			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/ObjectController/addBasicObject", postParameters);
			String res = result.toString();

			// res = res.trim();
			res = res.replaceAll("\\s+", "");
			if (Integer.parseInt(res) > 0) {
				Toast.makeText(this, "Add object successful",
						Toast.LENGTH_SHORT).show();
				addResToArray(Integer.parseInt(res));

			} else {
				Toast.makeText(this, "Add object fail", Toast.LENGTH_SHORT)
						.show();
			}

		} catch (Exception e) {

		}

	}

	private void addResToArray(int id_Res) {
		// TODO Auto-generated method stub

		JSONArray jArray;
		JSONObject json_data = null;
		int i;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Obj", String
				.valueOf(id_Res)));
		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/ObjectController/getObjectById", postParameters);

			jArray = new JSONArray(result);
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				// Log.d("A", json_data.getString("name"));
				jArr.put(json_data);
			}
		} catch (JSONException e1) {
			Toast.makeText(this, "addResToArray" + e1.toString(),
					Toast.LENGTH_SHORT).show();
		} catch (ParseException e1) {
			Toast.makeText(this, "addResToArray" + e1.toString(),
					Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void updateTime() {
		resTime.setText(dateAndTime.get(Calendar.HOUR_OF_DAY) + ":"
				+ dateAndTime.get(Calendar.MINUTE));
	}

}
